import { CheckGPU } from "./helper";
import { Shaders } from "./shader";

export const CreateTriangle = async(element:string,color:string) =>{
    const checkGPU = CheckGPU();
    if(!checkGPU){
        console.log("Your current browser does not support WebGPU!");
        throw("Your current browser does not support WebGPU!");
    };

    const parentNode = document.querySelector(element) as HTMLElement;
    const canvas = document.createElement("canvas");
    parentNode.appendChild(canvas);
    canvas.height = parentNode.clientHeight;
    canvas.width = parentNode.clientWidth;

    const adapter = await navigator.gpu?.requestAdapter() as GPUAdapter;
    const device = await adapter?.requestDevice() as GPUDevice;
    const ctx = canvas.getContext("webgpu")as unknown as GPUCanvasContext;

    const swapChainFormat = "bgra8unorm";
    // @ts-ignore
    const swapChain = ctx["configure"](device)({
        device: device,
        format: swapChainFormat
    });

    const shader = Shaders(color);
    const pipeline = device.createRenderPipeline({
            // @ts-ignore
        vertexStage:{
            module: device.createShaderModule({
                code: shader.vertex_shader
            }),
            entryPoint:"main"
        },
        fragmentStage:{
            module: device.createShaderModule({
                code: shader.fragment_shader
            }),
            entryPoint: "main"
        },
        primitiveToplolgy: "triangle-list",
        colorStates:[{
            format: swapChainFormat
        }]
    });

    // 渲染通道编码器
    const commandEncoder = device.createCommandEncoder();
    const textureView = swapChain.getCurrentTexture().createView();
    const renderPass = commandEncoder.beginRenderPass({
        colorAttachments:[{
            // @ts-ignore
            attachment: textureView,
            loadValue: [0.5,0.5,0.8,1.0] // 背景颜色
        }]
    });
    renderPass.setPipeline(pipeline); // 渲染管线添加到渲染通道上
    renderPass.draw(3,1,0,0); // 绘制
    renderPass.endPass();
    device.queue.submit([commandEncoder.finish()]);
};